package com.kevin.controller.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kevin.common.api.PageDTO;
import com.kevin.common.api.R;
import com.kevin.service.entity.SysLogLogin;
import com.kevin.service.query.SysLogLoginQuery;
import com.kevin.service.service.SysLogLoginService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 登录日志
 *
 * @author 阿沐 babamu@126.com
 */
@RestController
@RequestMapping("sys/log/login")
@Api(tags = "登录日志")
@AllArgsConstructor
public class SysLogLoginController {
    private final SysLogLoginService sysLogLoginService;
    private final Ip2regionSearcher ip2regionSearcher;

    @GetMapping("page")
    @ApiOperation(value = "分页")
    @SaCheckPermission(value = "sys:log:login")
    public R<PageInfo<SysLogLogin>> page(PageDTO pageDTO, SysLogLoginQuery query) {
        PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
        return R.ok(new PageInfo<>(listByQuery(query)));
    }

    @GetMapping("flushLoginAddress")
    @ApiOperation(value = "刷新ip地址")
    @SaCheckPermission(value = "sys:log:login")
    public R<?> flushLoginAddress() {
        List<SysLogLogin> list = sysLogLoginService.list();
        for (SysLogLogin sysLogLogin : list) {
            sysLogLogin.setAddress(ip2regionSearcher.getAddress(sysLogLogin.getIp()));
        }
        sysLogLoginService.updateBatchById(list);
        return R.ok();
    }

    private List<SysLogLogin> listByQuery(SysLogLoginQuery query) {
        return sysLogLoginService.list(Wrappers.lambdaQuery(SysLogLogin.class)
                .like(StrUtil.isNotBlank(query.getUsername()), SysLogLogin::getUsername, query.getUsername())
                .like(StrUtil.isNotBlank(query.getAddress()), SysLogLogin::getAddress, query.getAddress())
                .like(query.getStatus() != null, SysLogLogin::getStatus, query.getStatus())
                .orderByDesc(SysLogLogin::getId)
        );
    }

    @GetMapping("export")
    @ApiOperation(value = "分页")
    @SaCheckPermission(value = "sys:log:login")
    public void export(SysLogLoginQuery query, HttpServletResponse response) throws IOException {
        List<SysLogLogin> list = listByQuery(query);
        list.forEach(e -> {
            if (e.getStatus() != null) {
                e.setStatusStr(e.getStatus() == 0 ? "失败" : "成功");
            }
            e.setCreateTimeStr(DateUtil.formatDateTime(e.getCreateTime()));
        });
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("登录日志导出.xlsx", "utf-8"));
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        EasyExcel.write(response.getOutputStream(), SysLogLogin.class)
                .sheet("Sheet1")
                .doWrite(list);
    }

}
